<?php

namespace App\Http\Controllers\admin_system;

use App\Models\V1\ChapterModel;
use App\Models\V1\CloMemberInfo;
use App\Models\V1\LessonCenter;
use App\Models\V1\Lessons;
use App\Models\V1\LessonsBanner;
use App\Models\V2\LearningOfficerMatter;
use App\Models\V2\LessonCenterNotice;
use App\Module\EntBookInfo;
use App\Module\EntMindShare;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

class StudyCenterController extends Controller
{
    //添加banner
    public function banner(LessonsBanner $lessonsBanner)
    {
        $bookInfo  = EntBookInfo::where('DeleteMark', 1)->select('BookID', 'BookTitle')->get();
        $mindshare = EntMindShare::where('DeleteMark', 1)->select('MinSgaID', 'MinSgaTitle')->get();

        return view('admin_system.studyCenter.banner', compact('bookInfo', 'mindshare'));
    }




    public function banner_index(LessonsBanner $lessonsBanner, Request $request)
    {
        $sort   = $request->Input('sort', 'desc');
        $data   = $lessonsBanner->orderBy('id', $sort)->get();
        $types  =   [
            '1' => '学习官',
            '2' => '国政',
            'appindex'  => 'APP首页'
        ];

        foreach($data as $d)
        {
            $d->banner_type     = $types[$d->banner_type];
        }
        return view('admin_system.studyCenter.bannerIndex', compact('data'));
    }

    //删除banner
    public function banner_del(Request $request)
    {
        $id     = $request->Input('banner_id');
        $banner = LessonsBanner::find($id);
        if ($banner) {
            //删除图片
            unlink(public_path() . '/' . $banner->banner_img);
            LessonsBanner::destroy($id);
            return response()->json(['code' => '200', 'msg' => '删除成功']);
        } else {
            return response()->json(['code' => 400, 'msg' => '删除失败']);
        }
    }

    //更新
    public function banner_update(Request $request)
    {
        $banner_id    = $request->Input('banner_id');//banner的Id
        $lessons_id   = $request->Input('lessons_id');//lessons的Id
        $content_id   = $request->Input('content_id');//内容的ID
        $banner_title = $request->Input('banner_title');//banner的标题
        $content_type = $request->Input('content_type');
        $banner_type  = $request->Input('banner_type');

        $content_id   = $lessons_id ? $lessons_id : $content_id;

        $bannerInfo = [
            'banner_title'  => $banner_title,
            'banner_type'   => $banner_type,
            'content_type'  => $content_type,
            'content_id'    => $content_id,
        ];


        if ($request->hasFile('banner_img'))
        {
            $banner_img = $request->file('banner_img');
            $old_img    = LessonsBanner::find($banner_id);

            if ($banner_img->isValid()) //如果图片有效
            {
                //1.删除原来的图片
                $path = public_path()  . $old_img->banner_img;
                if(file_exists($path))
                {
                    unlink($path);
                }

                //2.更新新图片地址
                $ext         = $banner_img->getClientOriginalExtension();
                $newFileName = date('Y-m-d') . '-' . uniqid() . '.' . $ext;
                $direct      = public_path() . '/admin/images';
                $path        = '/admin/images/' . $newFileName;

                $banner_img->move($direct, $newFileName);
                $bannerInfo['banner_img']   = $path;
            }
        }
        LessonsBanner::where('id', $banner_id)->update($bannerInfo);
        return response()->json(['code' => 200, 'msg' => '更新成功啦']);
    }

    //更新显示
    public function banner_update_index(LessonsBanner $lessonsBanner, Request $request)
    {
        $url       = $request->header('referer');
        $id        = $request->Input('id');
        $type      = $request->Input('type');
        $bookInfo  = EntBookInfo::where('DeleteMark', 1)->select('BookID', 'BookTitle')->get();
        $mindshare = EntMindShare::where('DeleteMark', 1)->select('MinSgaID', 'MinSgaTitle')->get();
        if ($type == 1) {
            $lessons = $lessonsBanner->find($id)->hasLessonsOne;//获取课程信息
        } else {
            $lessons = null;
        }
        $bannerInfo = $lessonsBanner->find($id);
        return view('admin_system.studyCenter.bannerUpdateIndex', compact('lessons', 'bannerInfo', 'url', 'bookInfo', 'mindshare'));
    }

    public function ajaxSearchResponse(Request $request)
    {
        $query   = $request->Input('query');
        $lessons = Lessons::where('title', 'like', '%' . $query . '%')->get(['id as value', 'title as data']);
        return response()->json(['query' => "$query", 'suggestions' => json_encode($lessons)]);
        return response()->json(['query' => "$query", 'suggestions' => $lessons]);
    }

    //banner添加
    public function bannerUpload(Request $request)
    {
        if (!$request->Input('lessons_id') && !$request->Input('content_id')) {
            return response()->json(['code' => '400', 'msg' => '缺少参数']);
        }

        if ($request->hasFile('banner_img')) {
            $banner_img = $request->file('banner_img');
            if ($banner_img->isValid()) {
                $ext = $banner_img->getClientOriginalExtension();
                //新文件名
                $newFileName = date('Y-m-d') . '-' . uniqid() . '.' . $ext;
                $direct      = public_path() . '/admin/images';
                $banner_img->move($direct, $newFileName);
                $path       = '/admin/images/' . $newFileName;
                $lessons_id = $request->Input('lessons_id');
                $content_id = $request->Input('content_id');
                $id         = $lessons_id ? $lessons_id : $content_id;
                LessonsBanner::create(
                    [
                        'banner_img'   => $path,
                        'content_id'   => $id,
                        'banner_title' => $request->Input('banner_title'),
                        'banner_type'  => $request->Input('banner_type'),
                        'content_type' => $request->Input('content_type')
                    ]
                );
                return response()->json(['code' => '200', 'msg' => '上传成功']);
            } else {
                return response()->json(['code' => '400', 'msg' => '上传错误']);
            }
        } else {
            return response()->json(['code' => '400', 'msg' => '上传文件无效']);
        }


    }

    //视频列表
    public function lessons_list(Request $request)
    {
        $category = $request->Input('lessons_category_id', null);
        if ($category != null) {
            $data = Lessons::where('lessons_category_id', $category)->orderBy('created_at', 'desc')->paginate(5);
            $type = $category;
        } else if ($category == null) {
            $data = Lessons::orderBy('created_at', 'desc')->paginate(5);
            $type = null;
        }
        //获取所有的视频的分类
        $category = LessonCenter::all();
        return view('admin_system.studyCenter.lessons_list', compact('data', 'type', 'category'));
    }

    //视频删除
    public function lessons_del(Request $request)
    {
        $id     = $request->Input('id');
        $status = Lessons::destroy($id);
        if ($status) {
            return redirect()->back()->with(['success' => '删除成功']);
        } else {
            return redirect()->back()->with(['errors' => '删除失败']);
        }
    }

    //视频修改
    public function lessons_save(Request $request)
    {
        $id     = $request->Input('id');
        $status = Lessons::find($id);
        $status->fill($request->except(['_token', 'id']));
        $status->save();
        if ($status) {
            return redirect()->back()->with(['success' => '修改成功']);
        } else {
            return redirect()->back()->with(['errors' => '修改失败']);
        }
    }

    //视频添加
    public function lessons_add(Request $request)
    {
        $request['user_id'] = $request->Input('lessons_teacher');
        $data               = $request->except('_token');
        unset($request['lessons_teacher']);
//        dd($data);
        $lesson = Lessons::create($data);
        if ($lesson) {
            return redirect()->back()->with(['success' => '保存成功']);
        } else {
            return redirect()->back()->with(['errors' => '保存失败']);
        }
    }

    //学习官clo
    public function lessons_clo(Lessons $lessons)
    {
        //1.获取所有的clo信息
        $data = CloMemberInfo::orderBy('created_at', 'desc')->paginate(3);
        $clos = $lessons->clo_info();
        return view('admin_system.studyCenter.lessonsClo', compact('clos', 'data'));
    }

    //学习官修改
    public function lessons_clo_update(Request $request)
    {
        $clo_id            = $request->Input('clo_id');
        $cloInfo           = CloMemberInfo::find($clo_id);
        $data              = $request->except(['_token', 'clo_id']);
        $data['introduce'] = trim($request->Input('introduce'));
        if ($request->hasFile('user_img')) {
            $user_img = $request->file('user_img');
            if ($user_img->isValid()) {//用户重新上传图片
                $ext         = $user_img->getClientOriginalExtension();
                $newFileName = date('Y-m-d') . '-clo-' . uniqid() . '.' . $ext;
                $direct      = public_path() . '/admin/images';
                $user_img->move($direct, $newFileName);
                $path    = '/admin/images/' . $newFileName;
                $oldPath = public_path() . '/' . $cloInfo->user_img;
                unlink($oldPath);//删除以前的图片
                $data['user_img'] = $path;//保存新的图片
                $status           = $cloInfo->fill($data)->save();
            }
        } else {//用户没有选择上传图片
            $status = $cloInfo->fill($data)->save();//直接保存数据
        }

        if ($status) {
            return redirect()->route('lessons_clo');
        } else {
            return redirect()->back()->with(['errors' => '修改失败']);
        }
    }

    public function lessons_clo_show(Lessons $lessons, Request $request)
    {
        $id       = $request->Input('id');
        $clo_info = CloMemberInfo::find($id);
        $clos     = $lessons->clo_info();

        return view('admin_system.studyCenter.cloEditor', compact('clo_info', 'clos'));
    }

    //学习官删除
    public function lessons_clo_del(Request $request)
    {
        $clo_id   = $request->Input('id');
        $clo_info = CloMemberInfo::find($clo_id);
        if ($clo_info) {
            CloMemberInfo::destroy($clo_id);
            return response()->json(['code' => 200, 'msg' => '删除学习官成功']);
        } else {
            return response()->json(['code' => 200, 'msg' => '删除学习官失败']);
        }
    }

    //添加学习官
    public function lessons_clo_add(Request $request, CloMemberInfo $cloMemberInfo)
    {
        //1.暂时取消图片上传功能----
        $user_id   = $request->Input('clo_name');
        $introduce = trim($request->Input('introduce'));
        $title     = $request->Input('title');
        if ($request->hasFile('user_img')) {
            $user_img = $request->file('user_img');
            if ($user_img->isValid()) {//如果上传文件有效
                $ext = $user_img->getClientOriginalExtension();
                //新的文件名
                $newFileName = date('Y-m-d') . '-clo-' . uniqid() . '.' . $ext;
                $direct      = public_path() . '/admin/images';
                $user_img->move($direct, $newFileName);
                $path    = '/admin/images/' . $newFileName;
                $cloInfo = CloMemberInfo::create(['user_id' => $user_id, 'introduce' => $introduce, 'title' => $title, 'user_img' => $path]);
            }
        }
        if ($cloInfo) {
            return redirect()->back()->with(['success' => '添加学习官成功']);
        } else {
            return redirect()->back()->with(['errors' => '添加学习官失败']);
        }
    }

    //通知列表
    public function notice_list()
    {
        $notice = LessonCenterNotice::all();

        //获取关联文章和视频
        $article = LearningOfficerMatter::where('lessons_category_id', 1)->get();//获取文章
        $video   = LearningOfficerMatter::where('lessons_category_id', 2)->get();//获取视频

        return view('admin_system.studyCenter.noticeIndex', compact('notice', 'article', 'video'));
    }

    //通知删除
    public function notice_del(Request $request)
    {
        $id     = $request->Input('id');
        $status = LessonCenterNotice::destroy($id);
        if ($status) {
            return redirect()->back()->with(['notice_success' => '删除成功']);
        } else {
            return redirect()->back()->with(['notice_errors' => '删除失败']);
        }
    }

    //通知添加
    public function notice_add(Request $request)
    {
        $data      = $request->except('_token');
        $notice_id = $request->has('notice_id');
        if ($notice_id){
            LessonCenterNotice::create($data);
            return redirect()->back()->with(['notice_success'=>'添加成功']);
        }else{
            return redirect()->back()->withInput()->with(['notice_errors'=>'缺少参数','is_show'=>true]);
        }
    }

    //显示编辑
    public function notice_show(Request $request)
    {
        //获取关联文章和视频
        $article = LearningOfficerMatter::where('lessons_category_id', 1)->get();//获取文章
        $video   = LearningOfficerMatter::where('lessons_category_id', 2)->get();//获取视频
        $notice = LessonCenterNotice::find($request->id);

        return view('admin_system.studyCenter.noticeEdit',compact('article','notice','video'));
    }

    //更新数据
    public function notice_update(Request $request)
    {
        $data=$request->except('_token','id');
        $status=LessonCenterNotice::where('id',$request->route('id'))->update($data);
        if ($status){
            return redirect()->route('notice_list')->with(['notice_success'=>'更新成功']);
        }else{
            return redirect()->route('notice_list')->with(['notice_errors'=>'更新失败了']);
        }
    }

    //学习官中心的文章列表
    public function article_list()
    {
        $data=LearningOfficerMatter::orderBy('updated_at','desc')->paginate(5);

        return view('admin_system.studyCenter.articleIndex',compact('data'));
    }

    //学习官中心的文章删除
    public function article_del(Request $request)
    {

        $id=$request->route('id');
//        $article_img=LearningOfficerMatter::where('id',$id)->select('article_img')->first();
        $status=LearningOfficerMatter::destroy($id);
//        $article_img=$article_img->article_img;

        if ($status){
//            if (!preg_match('/http/',$article_img)){//非网络图片
//                unlink(public_path().$article_img);
//            }
            return redirect()->back()->with(['article_success'=>'删除成功']);
        }else{
            return redirect()->back()->with(['article_errors'=>'删除失败了']);
        }
    }

    //学习官中心的文章添加
    public function article_add(Request $request)
    {
        return view('admin_system.studyCenter.articleAdd');
    }

    //保存文章
    public function article_save(Request $request)
    {
        if ($request->hasFile('article_img')){
            $file=$request->file('article_img');
            $ext=$file->getClientOriginalExtension();
            $fileNewName=date('Y-m-d').'-article_img-'.uniqid().'.'.$ext;
            $dir=public_path().'/admin/study_center_article';
            $file->move($dir,$fileNewName);
            $article_img='/admin/study_center_article/'.$fileNewName;
            LearningOfficerMatter::create([
                'lessons_category_id'=>$request->Input('lessons_category_id'),
                'title'=>$request->Input('title'),
                'article_img'=>$article_img,
                'body'=>$request->Input('body'),
                'introduce'=>$request->Input('introduce')
            ]);
            return redirect()->route('article_list')->with(['article_success'=>'添加成功']);
        }
    }

    //文章里面的图片
    public function article_img_upload(Request $request)
    {
        if ($request->hasFile('article_content_img')){
            $file=$request->file('article_content_img');
            $ext=$file->getClientOriginalExtension();
            $fileNewName=date('Y-m-d').'-article-'.uniqid().'.'.$ext;
            $directory=public_path().'/admin/study_center_article/';
            $file->move($directory,$fileNewName);
            return response()->json(['errno'=>0,'data'=>['/admin/study_center_article/'.$fileNewName]]);
        }
    }

    //文章的编辑
    public function article_edit(Request $request)
    {
        $id=$request->route('id');
        $data=LearningOfficerMatter::find($id);
        return view('admin_system.studyCenter.articleEdit',compact('data'));
    }

    //文章编辑保存
    public function article_edit_save(Request $request)
    {
        $id=$request->route('id');
        if ($request->hasFile('article_img')){//如果用户重新上传了封面
            $file=$request->file('article_img');
            $old_img=LearningOfficerMatter::select('article_img')->where('id',$id)->first();
            $old_img_path=$old_img->article_img;
            if (!preg_match('/http/',$old_img_path)){//非网络图片
                $path=public_path().$old_img_path;
                unlink($path);
            }
            $ext=$file->getClientOriginalExtension();
            $fileNewName=date('Y-m-d').'-article_img-'.uniqid().'.'.$ext;
            $dir=public_path().'/admin/study_center_article';
            $file->move($dir,$fileNewName);
            $article_img='/admin/study_center_article/'.$fileNewName;
            LearningOfficerMatter::where('id',$id)->update([
                'lessons_category_id'=>$request->Input('lessons_category_id'),
                'title'=>$request->Input('title'),
                'article_img'=>$article_img,
                'body'=>$request->Input('body'),
                'introduce'=>$request->Input('introduce')
            ]);
            return redirect()->route('article_list')->with(['article_success'=>'编辑成功']);
        }else{//用户没有重新上传新的图片
            LearningOfficerMatter::where('id',$id)->update([
                'lessons_category_id'=>$request->Input('lessons_category_id'),
                'title'=>$request->Input('title'),
                'body'=>$request->Input('body'),
                'introduce'=>$request->Input('introduce')
            ]);
            return redirect()->route('article_list')->with(['article_success'=>'编辑成功']);
        }
        return redirect()->back()->with(['article_errors'=>'编辑失败']);
    }
}



























